<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use JMessage\JMessage;
use JMessage\IM\Message;
use JMessage\IM\User;
/**
* 定单控制器
*/
class OrderController extends Controller
{
	/*
		服务列表
	*/
	public function servicelist()
	{
		$arr = [];
		//查询服务表
		$re = Db :: table('server_item')->where('parent_id',0)->select('id','name')->get();
		$re = json_decode(json_encode($re),true);
		$arr['data'] = $re;
		//dump($re);
		$arr['msg'] = '请求成功';
		$arr['code'] = '200';
		echo json_encode($arr);
	}
	/*
		订单列表
	*/
	public function orderlist(Request $request)
	{
		//订单状态
		$whereStatus = $request['whereIn'];
		//dump($whereStatus);
		//订单分类
		//dump($whereStatus);
		if(in_array('0',$request['parent_id'])){
			$whereItem = [];
			$re = Db :: table('server_item')->where('parent_id',0)->select('id','name')->get();
			$re = json_decode(json_encode($re),true);
			foreach ($re as $key => $value) {
				$whereItem[] = $value['id'];
			}
		}else{
			$whereItem = $request['parent_id'];
		}
		//dump($whereItem);
		//订单来源
		if(in_array('0', $request['whereSource'])){
			$whereSource = [1,2,3,4,5];
		}else{
			$whereSource = $request['whereSource'];
		}
			//dump($whereSource);
		//计费模式
		if(in_array('0',$request['whereCharging'])){
			$whereCharging = [1,2,3];
		}else{
			$whereCharging = $request['whereCharging'];
		}
			//dump($whereCharging);
		//dump(1);
		//计算页数
		$total = DB :: table('order')
			->leftJoin('server_item','order.typeid','=','server_item.id')
			->whereIn('order.orderstatus',$whereStatus)
			->whereIn('order.typeid',$whereItem)
			->whereIn('order.source',$whereSource)
			->whereIn('order.charging',$whereCharging)
			->orderBy('order.createtime','desc')
			->count();
		//查询订单	
		$re = DB :: table('order')
			->leftJoin('server_item','order.typeid','=','server_item.id')
			->whereIn('order.orderstatus',$whereStatus)
			->whereIn('order.typeid',$whereItem)
			->whereIn('order.source',$whereSource)
			->whereIn('order.charging',$whereCharging)
			->orderBy('order.createtime','desc')
			->select('order.id','order.orderstatus','order.source','order.usetime','order.original','order.end','order.createtime','order.orderstatus','server_item.name','server_item.parent_id')
			->paginate(2);
		//dump($re);
		$data = json_decode(json_encode($re),true);
		//dump($data);
		if(!empty($data)){
			foreach ($data['data'] as $key => &$value) {
				$value['usetime'] = date('Y-m-d H:i',$value['usetime']);
				$value['source'] = $this -> orderSource($value['source']);
				$value['orderstatus'] = $this -> orderStatus($value['orderstatus']);
				$re[$key] = $value;
			}
		}else{
			$data = $data;
		}
		$returnArr['total'] = floor($total / 2);
		$returnArr['msg'] = '请求成功';
		$returnArr['data'] = $data['data'];
		$returnArr['code'] = '200';
		echo json_encode($returnArr);
	}
	/*
		订单来源
	*/
	private function orderSource($value)
	{
			switch ($value) {
				case 1:
					return 'app';
					break;
				case 2:
					return '后台';
					break;
				case 3:
					return '酒店前台';
					break;
				case 4:
					return '网约车小程序';
					break;
				default:
					return '社会化用车';
					break;
			}
	}
	/*
		订单状态
	*/
	private function orderStatus($value)
	{
		switch ($value) {
				case 1:
					return '未派单';
					break;
				case 2:
					return '带执行';
					break;
				case 3:
					return '执行中';
					break;
				case 4:
					return '已完成';
					break;
				case 5:
					return '已取消';
					break;
				default:
					return '未知状态';
					break;
			}
	}
	/**
	 * 订单执行状态
	 */
	private function orderExcute($value)
	{
		switch ($value) {
				case 1:
					return '未派单';
					break;
				case 2:
					return '指派司机';
					break;
				case 3:
					return '司机接单';
					break;
				case 4:
					return '备车';
					break;
				case 5:
					return '前往预约地';
					break;
				case 6:
					return '到达指定地';
					break;
				case 7:
					return '开始服务';
					break;
				case 8:
					return '即将到达';
					break;
				default:
					return '结束服务';
					break;
			}
	}
		/*
		订单状态
	*/
	private function attendant($value)
	{
		switch ($value) {
				case 1:
					return '载客';
					break;
				case 2:
					return '接单';
					break;
				case 3:
					return '空驶';
					break;
				case 4:
					return '停运';
					break;
				case 5:
					return '休假';
					break;
				default:
					return '离职';
					break;
			}
	}
	/*
		订单详情
	*/
	public function orderDetail(Request $request)
	{
		$id = $request['id'];
		$re = Db :: table('order')
			->leftJoin('order_extend','order.extendid','=','order_extend.id')
			->leftJoin('server_item','order.typeid','=','server_item.id')
			->leftJoin('social_user','order.uid','=','social_user.id')
			->leftJoin('car_series','order.carserid','=','car_series.id')
			->where('order.id',$id)
			->select('server_item.name','order.num','order.source','order_extend.fightnum','order.usetime','order.sumpeople','order_extend.driver_id','order.original','order.end','order.uid','order_extend.passenger_name','order_extend.passenger_phone','order_extend.cip_info','order.createtime','order.charging','order_extend.cip_num','order.originaldegree','order.enddegree','order.reassignment','social_user.nickname','social_user.phone','order.beizhu','order.orderstatus','car_series.name')
			->first();
		$data = json_decode(json_encode($re),true);
		$data['source'] = $this->orderSource($data['source']);
		$data['usetime'] = date('Y-m-d H:i',$data['usetime']);
		$arr['data']['info'] = $data;
		$arr['data']['cip'] = $data['cip_info'];
		//司机和车辆的信息
		if(!empty($data['driver_id'])){
			$carInfo = Db :: table('driver')
				->leftJoin('car_car','driver.car_id','=','car_car.id')
				->leftJoin('car_type','car_car.typeid','=','car_type.id')
				->leftJoin('car_series','car_type.sid','=','car_series.id')
				->select('driver.id','driver.driver_name','driver.driver_phone','driver.user_pic','car_car.num','car_car.color','car_series.name')
				->first();
			$carInfo = json_decode(json_encode($carInfo),true);
		}else{
			$carInfo = '';
		}
		$arr['data']['carDriver'] = $carInfo;
		//价格集合
		$price = Db :: table('order_price')->where('oid',$id)->first();
		$price = json_decode(json_encode($price),true);
		foreach ($price as $key => &$value) {

			if(empty($value)){
				$value = '';
			}
		}
		$arr['data']['price'] = $price;
		//里程及用时
		$long = Db :: table('order_long')->where('oid',$id)->first();
		$long = json_decode(json_encode($long),true);
		
		$arr['data']['long'] = $long;
		//订单状态
		$status = Db :: table('order_status')->where('order_number',$data['num'])->select('status','update_time')->get();
		$status = json_decode(json_encode($status),true);
		
		//确定进行到哪一步
		$statusFlag = 0;
		foreach ($status as $key => &$value) {
			$value['update_time'] = date('Y-m-d H:i:s',$value['update_time']);
			if($statusFlag < $value['status']){
				$statusFlag = $value['status'];
			}
			$value['status'] = $this->orderExcute($value['status']);
			
		}
		$arr['data']['status'] = $status;
		//添加为执行的状态
		for ($i = $statusFlag+1; $i < 10; $i++) { 
			$arr['data']['status'][] = [
					'status'=>$this->orderExcute($i),
					'update_time'=>''
				];
		}
		$arr['data']['statusFlag'] = (int)$statusFlag;
		
		$arr['code'] = '200';
		$arr['msg'] = '请求成功';
		echo json_encode($arr);
	}
	/*
		改派历史
	*/
	public function changeHistory(Request $request)
	{
		$id = $request['id'];
		$re = Db :: table('order_reassignment')
			->where('oid',$id)->get();
		$data = json_decode(json_encode($re),true);
		if(!empty($data)){
			foreach ($data as $key => &$value) {
				$value['info'] = json_decode($value['info'],true);
			}
		}
		$arr['data'] = $data;
		$arr['code'] = '200';
		$arr['msg'] = '请求成功';
		echo json_encode($arr);
	}
	/*
		取消订单
	*/
	public function delOrder(Request $request)
	{
		$id = $request['id'];
		$order = Db :: table('order')->where('id',$id)->select('num')->first();
		$data = json_decode(json_encode($order),true);
		DB::beginTransaction();
        try {
        	//修改订单状态
        	Db :: table('order')->where('id',$id)->update(['orderstatus'=>5]);
        	//记录订单状态
        	// $arr = [
        	// 	'order_number'=>$data['num'],
        	// 	'status'=>5,
        	// 	'update_time'=>date('Y-m-d H:i:s',time())
        	// ];
        	// Db :: table('order_status')->insert($arr);
        	//退钱

        	DB::commit();
        } catch (\Exception $e) {
        	DB::rollBack();
        	$arr['code'] = '201';
        	$arr['msg'] = '数据库操作失败';
        	$arr['info'] = $e;
        	return json_encode($arr);
        	
        }
        $arr['code'] = '200';
        $arr['msg'] = '操作成功';
        return json_encode($arr);
	}
	/*
		派单司机列表
	*/
	public function driverList(Request $request)
	{
		$id = $request['id'];//订单id
		$orderDis = $request['orderDis'];//按距离排序  1正 2倒   默认1
		$orderSer = $request['orderSer'];//按服务次数排序  1正 2倒  默认1
		$types = $request['types'];//1为该客户提供过服务    2推荐司机
		$uid = Db :: table('order') -> where('id',$id)->select('uid','originaldegree','areacode')->first();
		if($types == 1){
			//查询为该用户服务过的司机信息
			$re = Db :: table('order')
					->leftJoin('order_extend','order.extendid','=','order_extend.id')
					->rightJoin('driver','order_extend.driver_id','=','driver.id')
					->leftJoin('car_car','driver.car_id','=','car_car.id')
					->leftJoin('car_type','car_car.typeid','=','car_type.id')
					->leftJoin('car_series','car_type.sid','=','car_series.id')
					->leftJoin('branch','car_car.teamid','=','branch.id')
					->leftJoin('convoy','driver.convoy_id','=','convoy.id')
					->where('car_car.area',$uid->areacode)
					->where('order.uid',$uid->uid)
					->groupBy('order_extend.driver_id')
					->select('driver.id','driver.driver_name','driver.driver_phone','driver.user_pic','driver.attendant','car_series.pic','car_car.num','car_car.color','car_series.name as sname','branch.company_name','branch.type','convoy.name')
					->paginate(1);
			//dump($re);
			$data = json_decode(json_encode($re),true);
			if(empty($data['data'])){
				$arr['data'] = '';
				$arr['code'] = '201';
				$arr['msg'] = '没有司机为该乘客提供过服务';
				return json_encode($arr);
			}
		}else{
			//推荐司机
			$where = [];
			//公司类型
			if(!empty($request['companyType'])){
				$where['branch.type'] = $request['companyType'];
			}
			//公司名称
			if(!empty($request['companyName'])){
				$where['branch.id'] = $request['companyName'];
			}
			//车系
			if (!empty($request['carSeries'])) {
				$where['car_series.id'] = $request['carSeries'];
			}
			//车队
			if(!empty($request['carTeam'])){
				$where['convoy.id'] = $request['carTeam'];
			}
			//司机
			if (!empty($request['carDriver'])) {
				$where['driver.id'] = $request['carDriver'];
			}
			$re = Db :: table('driver')
					->leftJoin('car_car','driver.car_id','=','car_car.id')
					->leftJoin('car_type','car_car.typeid','=','car_type.id')
					->leftJoin('car_series','car_type.sid','=','car_series.id')
					->leftJoin('branch','car_car.teamid','=','branch.id')
					->leftJoin('convoy','driver.convoy_id','=','convoy.id')
					->where('car_car.area',$uid->areacode)
					->where($where)
					->select('driver.id','driver.driver_name','driver.driver_phone','driver.user_pic','driver.attendant','car_series.pic','car_car.num','car_car.color','car_series.name as sname','branch.company_name','branch.type','convoy.name')
					->paginate(1);
			$data = json_decode(json_encode($re),true);

			if(empty($data['data'])){
				$arr['data'] = '';
				$arr['code'] = '201';
				$arr['msg'] = '没有司机入驻';
				return json_encode($arr);
			}
		}
		$arr['total'] = floor($data['total']/1);
			//取出所有司机手机号
		$phone = '';
		for ($i=0; $i < count($data['data']); $i++) { 
				if($i < count($data['data']) - 1){
					$phone = $phone . $data['data'][$i]['driver_phone'] . ',';
				}else{
					$phone = $phone . $data['data'][$i]['driver_phone'];
				}
		}
		//dump($phone);
		//计算司机到出发点的距离
		$position = $this->driverPosition($phone);
		//dump($position);
		$ori = implode('|', $position['data']);
		
		//dump($ori);
		$originaldegree = $uid -> originaldegree;
		$desArr = explode(',', $originaldegree);
		$des = $desArr[1] . ',' . $desArr[0];
		$dis = $this->countdis($ori,$des);
		//dump($dis);
		$disArr = $dis['data'];
		//dump($disArr);
		//按顺序把距离付给每一个司机
		$i = 0;
		foreach ($data['data'] as $key => &$value) {
			//计算司机总的服务次数
			$count = Db :: table('order')
						->leftJoin('order_extend','order.extendid','=','order_extend.id')
						->where('order.uid',$uid->uid)
						->where('order_extend.driver_id',$value['id'])
						->count();
			$value['countService'] = $count;
			//赋值距离
			$value['distance'] = $disArr[$i]['distance'];
			//查询司机最近3天的订单
			$threeAgo = time() + 3600*24*3;
			//dump($threeAgo);
			$now = time();
			//dump($now);
			$implementstatus = [3,4,5,6,7,8];
			//dump($value['id']);
			$useCarInfo = Db :: table('order')
							->leftJoin('order_extend','order.extendid','=','order_extend.id')
							->where('order_extend.driver_id',$value['id'])
							->whereBetween('order.usetime',[$now,$threeAgo])
							->whereIn('order.implementstatus',$implementstatus)
							->orderBy('order.id','desc')
							->select('order.original','order.end','order.usetime','order.implementstatus')
							->first();
			$useCarInfo = json_decode(json_encode($useCarInfo),true);
			//dump($useCarInfo);
			if(!empty($useCarInfo)){
				$useCarInfo['usetime'] = ($useCarInfo['usetime'] - time())/60;
			}
			$value['useCarInfo'] = $useCarInfo;
			$value['attendant'] = $this->attendant($value['attendant']);
			$i ++;
					//dump($useCarInfo);
		}
		//根据筛选排序
		if(!empty($request['orderDis'])){
			if($orderDis == 1){
				$returnArr = $this->my_sort($data['data'],'distance',SORT_ASC);
			}else{
				$returnArr = $this->my_sort($data['data'],'distance',SORT_DESC);
			}
		}
		if(!empty($request['orderSer'])){
			if($orderSer == 1){
				$returnArr = $this->my_sort($data['data'],'countService',SORT_ASC);
			}else{
				$returnArr = $this->my_sort($data['data'],'countService',SORT_DESC);
			}
		}
				
		//dump($returnArr);
		$arr['data'] = $returnArr;
		$arr['code'] = '200';
		$arr['msg'] = '请求成功';		
		echo json_encode($arr);	
	}
	/*
		人工推荐筛选条件公司接口
	*/
	public function selectConditionCom()
	{
		//公司
		$branch = Db :: table('branch')->select('id','company_name')->get();
		$branch = json_decode(json_encode($branch),true);
		
		$arr['data'] = $branch;
		$arr['code'] = '200';
		$arr['msg'] = '请求成功';
		echo json_encode($arr);
	}
	/*
		人工推荐筛选条件车队接口
	*/
	public function selectCondition(Request $request)
	{
		$where = [];
		if(!empty($request['id'])){
			$where['convoy.branch_id'] = $request['id'];
		}
		//车队
		$convoy = Db :: table('convoy')
					->where($where)
					->select('convoy.id','convoy.name')->get();
		$convoy = json_decode(json_encode($convoy),true);
		$arr['data'] = $convoy;
		
		$arr['code'] = '200';
		$arr['msg'] = '请求成功';
		echo json_encode($arr);
	}
		/*
		人工推荐筛选条件车系接口
	*/
	public function selectConditionComS(Request $request)
	{
		$where = [];
		if(!empty($request['id'])){
			$where['driver.convoy_id'] = $request['id'];
		}
		//车系
		$car_series = Db :: table('car_series')
						->leftJoin('car_type','car_type.sid','=','car_series.id')
		                ->leftJoin('car_car','car_type.id','=','car_car.typeid')
		                ->leftJoin('driver','car_car.id','=','driver.car_id')
		                ->where($where)
		                ->select('car_series.id','car_series.name','car_car.id as carid','driver.id as did')->get();
		$car_series = json_decode(json_encode($car_series),true);
		$car_series = $this->arr_uniq($car_series,'id');
		$arr['data']= $car_series;
		$arr['code'] = '200';
		$arr['msg'] = '请求成功';
		echo json_encode($arr);
	}
	/*
		人工推荐筛选条件司机接口
	*/
	public function selectConditionComD(Request $request)
	{
		$where = [];
		if(!empty($request['id'])){
			$where['car_series.id'] = $request['id'];
		}
		if(!empty($request['tid'])){
			$where['driver.convoy_id'] = $request['tid'];
		}
		//司机
		$driver = Db :: table('driver')
					->leftJoin('car_car','driver.car_id','=','car_car.id')
					->leftJoin('car_type','car_car.typeid','=','car_type.id')
					->leftJoin('car_series','car_type.sid','=','car_series.id')
					->where($where)
					->select('driver.id','driver.driver_name')->get();
		$driver = json_decode(json_encode($driver),true);
		
		$arr['data'] = $driver;
		$arr['code'] = '200';
		$arr['msg'] = '请求成功';
		echo json_encode($arr);
	}
	    /**
     * 二维数组按照指定键值去重
     * @param $arr 需要去重的二维数组
     * @param $key 需要去重所根据的索引
     * @return mixed
     */
	function arr_uniq($arr,$key)
	{
	    $key_arr = [];
	    foreach ($arr as $k => $v) {
	        if (in_array($v[$key],$key_arr)) {
	            unset($arr[$k]);
	        } else {
	            $key_arr[] = $v[$key];
	        }
	    }
	    sort($arr);
	    return $arr;
	}
	/*
		派单
	*/
	public function Distributeleaflets(Request $request)
	{
		$driverId = $request['driverId'];
		$orderId = $request['orderId'];
		$dispatchid = session('uid');
		//dump($dispatchid);die;
		$order = Db :: table('order')->where('id',$orderId)->select('extendid','num')->first();
		$order = json_decode(json_encode($order),true);
		$driver = Db :: table('driver')
					->leftJoin('car_car','driver.car_id','=','car_car.id')
					->leftJoin('car_type','car_car.typeid','=','car_type.id')
					->leftJoin('car_series','car_type.sid','=','car_series.id')
					->leftJoin('branch','car_car.teamid','=','branch.id')
					->leftJoin('convoy','driver.convoy_id','=','convoy.id')
					->where('driver.id',$driverId)
					->select('driver.sex','driver.driver_name','driver.driver_phone','branch.company_name','branch.type','car_car.num','car_series.name','convoy.name','driver.car_id')
					->first();
		$driver_info = json_decode(json_encode($driver),true);
		$admin = Db :: table('user')->where('id',$dispatchid)->select('name')->first();
		//dump($admin);die;
		//更新各个表的状态
		DB::beginTransaction();
		try {
        	//修改订单状态
        	Db :: table('order_extend')
        		->where('id',$order['extendid'])->update([
        			'driver_id'=>$driverId,
        			'driver_info'=>json_encode($driver_info)
        		]);
        	Db :: table('order_reassignment')->insert([
        		'oid'=> $orderId,
        		'name' => $driver_info['driver_name'],
        		'sex'=>$driver_info['sex'],
        		'phone'=>$driver_info['driver_phone'],
        		'info'=>json_encode($driver_info),
        		'type'=>$driver_info['type'],
        		'status'=>2,
        		'nextstatus'=>2,
        		'people'=>$admin -> name,
        		'time'=>date('Y-m-d H:i:s',time())
        	]);
        	Db :: table('order')->where('id',$orderId)->update(['implementstatus'=>2,'orderstatus'=>2,'dispatchid'=>$dispatchid]);	
        	Db :: table('order_status')->insert([
        		'order_number'=>$order['num'],
        		'status'=>2,
        		'update_time'=>date('Y-m-d H:i:s',time()),
        	]);
        	Db :: table('driver')->where('id',$driverId)->update(['attendant'=>2]);
        	Db :: table('car_car')->where('id',$driver_info['car_id'])->update(['status'=>2]);
        	DB::commit();
        } catch (\Exception $e) {
        	dump($e);
        	$arr['code'] = '201';
        	$arr['msg'] = '数据库操作失败';
        	$arr['info'] = $e;
        	DB::rollBack();
        	return json_encode($arr);
        }
        $arr['code'] = '200';
        $arr['msg'] = '操作成功';
        return json_encode($arr);
	}
	/**
		司机订单列表
	*/
	public function driverOrderLis(Request $request)
	{
		$driverId = $request['driverId'];
		$types = $request['types'];//1企业订单，2个人订单
		$re = Db :: table('order')
				->leftJoin('order_extend','order.extendid','=','order_extend.id')
				->leftJoin('user','order.dispatchid','=','user.id')
				->leftJoin('server_item','order.typeid','=','server_item.id')
				->where('order_extend.driver_id',$driverId)
				->where('order_extend.type',$types)
				->select('order.id','server_item.name','order.original','order.end','order.usetime','order.createtime','order_extend.passenger_name','order.passenger_phone','order.source','order.orderstatus','user.name','user.phone')
				->paginate(6);
		$data = json_decode(json_encode($re),true);
		$arr['data'] = $data['data'];
		$arr['code'] = '200';
		$arr['msg'] = '请求成功';
		echo json_encode($arr);
	}
	/*
		改派页面--司机的信息
	*/
	public function changeDriver(Request $request)
	{
		$orderId = $request['orderId'];
		$re = Db :: table('order')
				->leftJoin('order_extend','order.extendid','=','order_extend.id')
				->leftJoin('driver','order_extend.driver_id','=','driver.id')
				->leftJoin('car_car','driver.car_id','=','car_car.id')
				->leftJoin('car_type','car_car.typeid','=','car_type.id')
				->leftJoin('car_series','car_type.sid','=','car_series.id')
				->leftJoin('branch','car_car.teamid','=','branch.id')
				->leftJoin('convoy','driver.convoy_id','=','convoy.id')
				->where('order.id',$orderId)
				->select('driver.id','driver.driver_name','driver.driver_phone','driver.user_pic','driver.attendant','car_series.pic','car_car.num','car_car.color','car_series.name','branch.company_name','branch.type','convoy.name','order.originaldegree')
				->first();
		$data = json_decode(json_encode($re),true);
		$phone = $data['driver_phone'];
			
		//计算司机到出发点的距离
		$position = $this->driverPosition($phone);
		//dump($position);
		$ori = implode('|', $position['data']);
		//dump($ori);
		$originaldegree = $data['originaldegree'];
		$desArr = explode(',', $originaldegree);
		$des = $desArr[1] . ',' . $desArr[0];
		$dis = $this->countdis($ori,$des);
		//dump($dis);
		//计算司机总的服务次数
		$uid = Db :: table('order')->where('id',$orderId)->select('uid','originaldegree')->first();
		$count = Db :: table('order')
					->leftJoin('order_extend','order.extendid','=','order_extend.id')
					->where('order.uid',$uid->uid)
					->where('order_extend.driver_id',$data['id'])
					->count();
		$data['countService'] = $count;
		//赋值距离
		$data['distance'] = $dis['data'][0]['distance'];
		$arr['data'] = $data;
		$arr['code'] = '200';
		$arr['msg'] = '请求成功';
		echo json_encode($arr);
			
	}
	/*
		改派司机-提交改派原因
	*/
	public function changeDriverBecause(Request $request)
	{
		
		$orderId = $request['orderId'];

		$uid = Db :: table('user')->where('id',session('uid'))->select('name')->first();
		
		DB::beginTransaction();
        try {
        	Db :: table('order_reassignment')
		           ->where('oid',$orderId)->where('status',2)->update([
		           		'status'=>1,
					    'because'=>$request['because'],
					    'people'=>$uid->name,
					    'restime'=>date('Y-m-d H:i:s',time())
		           ]);
			Db :: table('order')->where('id',$orderId)->update([
						'orderstatus'=>1,
						'implementstatus'=>1
					]);
        	DB::commit();
        } catch (\Exception $e) {
        	DB::rollBack();
        	$arr['code'] = '201';
        	$arr['msg'] = '数据库操作失败';
        	$arr['info'] = $e;
        	return json_encode($arr);	
        }
		$arr['code'] = '200';
        $arr['msg'] = '操作成功';
		echo json_encode($arr);
	}
	/**
	 * 更改用车时间
	 */
	public function changeTime(Request $request)
	{
		Db :: table('order')->where('id',$request['id'])->update([
			'usetime'=>strtotime($request['time'])
			]);
		$arr['code'] = '200';
		$arr['msg'] = '请求成功';
		echo json_encode($arr);
	}
	/**
	 * 司机时时位置
	 */
	public function driverP(Request $request)
	{
		$id = $request['id'];
		$driver_phone = Db :: table('order')
						->leftJoin('order_extend','order.extendid','=','order_extend.id')
						->leftJoin('driver','order_extend.driver_id','=','driver.id')
						->select('driver.driver_phone','order.enddegree')->first();
		$phone = $driver_phone -> driver_phone;
		$retuenArr = [];
		//$phone= 17600184087;
		$driverPosition = $this->driverPosition($phone);
		if($driverPosition['code'] == '200'){
			$p = $driverPosition['data'][0];
		}else{
			$p = '';
		}
		$retuenArr['data']['position'] = $p;
		$enddegree = $driver_phone -> enddegree;
		$desArr = explode(',', $enddegree);
		$des = $desArr[1] . ',' . $desArr[0];
		$dis = $this->countdis($p,$des);
		$retuenArr['data']['distance'] = $dis['data'][0]['distance'];
		$retuenArr['data']['time'] = $dis['data'][0]['time'];
		$retuenArr['code'] = '200';
		$retuenArr['msg'] = '请前成功';
		echo json_encode($retuenArr);

	}
	/*
		二维数组按某个键排序 
		SORT_ASC - 默认，按升序排列。(A-Z)
		SORT_DESC - 按降序排列。(Z-A)
	*/
	function my_sort($arrays,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC ){   
        if(is_array($arrays)){   
            foreach ($arrays as $array){   
                if(is_array($array)){   
                    $key_arrays[] = $array[$sort_key];   
                }else{   
                    return false;   
                }   
            }   
        }else{   
            return false;   
        }  
        array_multisort($key_arrays,$sort_order,$sort_type,$arrays);   
        return $arrays;   
    }  
	/*
		$ori  起点
		$des 终点
		计算两点之间的距离
	*/
	public function countdis($ori,$des)
	{
		//$ori = '39.916566441207,116.47672599552|40.047452206531,116.44685440027';
		//$des = '40.086792,116.594566';
		//dump($ori);
		$url = 'http://api.map.baidu.com/routematrix/v2/driving?output=json&origins=' . $ori . '&destinations=' . $des . '&ak=RGwhFRkSZfva32BN96csoObm4FIfiCAY';
		$re = $this->get_curl_json($url);
		//dump($re);
		if($re['status'] == 0){
			$arr['code'] = '200';
			$arr['msg'] = '请求成功';
			$i = 0;
			foreach ($re['result'] as $key => $value) {
				$arr['data'][$i]['distance'] = $value['distance']['text'];
				$arr['data'][$i]['time'] = $value['duration']['text'];
				$i++;
			}
		}else{
			$arr['code'] = '500';
			$arr['msg'] = '百度服务器错误';
			$arr['data'] = '';
		}
		return $arr;
	}
	/*
		计算司机时时位置
	*/
	private function driverPosition($value)
	{
		//$value = '17710527453,17600184087';
		$ak = 'RGwhFRkSZfva32BN96csoObm4FIfiCAY';
		$serid = 158008;
		$url = 'http://yingyan.baidu.com/api/v3/entity/list?ak='.$ak.'&service_id='.$serid.'&filter=entity_names:'.$value;
		$re = $this->get_curl_json($url);
		//dump($re);
		//$re = json_decode($re,true);
		if($re['status'] == 0){
			$arr['code'] = '200';
			$arr['msg'] = '请求成功';
			foreach ($re['entities'] as $key => $value) {
				$arr['data'][] = $value['latest_location']['latitude'] .','.$value['latest_location']['longitude'] ;
			}
		}else{
			$arr['code'] = '500';
			$arr['msg'] = '百度服务器错误';
			$arr['data'] = '';
		}
		return $arr;
	}
	/**
     * 模拟get请求
     * @param $url
     * @return mixed
     */
    private function get_curl_json($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        $result = curl_exec($ch);
        if(curl_errno($ch)){
            print_r(curl_error($ch));
        }
        curl_close($ch);
        return json_decode($result,TRUE);
    }
    public function test()
    {
    	 $client = new JMessage('e3aa521e067467d9e4dba5bb','1ec040fbba99095178d35521');
//     	 $user = new User($client);
// $response = $user->listAll(10, 0);
    	//$response= $user->show('jiguang');
    	 $ms = new Message($client);
    	/* $message =[
            "extras" => array(
                'status'=> '130',
                'data' =>''
            )
        ];
         $alert = '【时代出行】时代小秘书温馨提示:员工的订单已完成，司机顺利将乘客送达目的地，希望再次为您服务！点击查看详情';
    	 $result = $client->push()
            ->setPlatform('all')
            ->options(['apns_production'=>true])
            ->addRegistrationId('121c83f760740501348')
            ->iosNotification($alert, $message)
            ->androidNotification($alert, $message)
            ->send();*/
            $from = [
			    'id'   => 'admin',
			    'type' => 'admin'
			];

			$target = [
			    'id'   => 'jiguang',
			    'type' => 'single'
			];
			$msg = [
			   'text' => 'Hello World'
			];
            $response = $ms->sendText(1, $from, $target, $msg);
            dump($response);
         
    }
    /**
     * 向特定设备推送消息
     * @param $regid   接收推送的设备标识
     * @param $alert   消息标题
     * @param $message 需要推送的消息体
     * @return mixed
     */
    public function sendNotifySpecial($regid, $alert, $message)
    {
        $client = new Client($this->appKey,$this->master_secret);
        if(empty($regid)){
            return;
        }
        $result = $client->push()
            ->setPlatform('all')
            ->options(['apns_production'=>true])
            ->addRegistrationId($regid)
            ->iosNotification($alert, $message)
            ->androidNotification($alert, $message)
            ->send();

        return Common::json_array($result);
    }
}